package com.example.repository;

import com.example.data.User.User;
import com.example.mappers.UserRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User queryUserById(long id) {
        String sql = "SELECT * FROM user WHERE id=? ";
        User user = jdbcTemplate.queryForObject(sql, new UserRowMapper(), id);
        return user;
    }


    public List<User> queryAllUser() {
        String sql = "SELECT * FROM user ORDER BY id";
        List<User> userList = jdbcTemplate.query(sql, new UserRowMapper());
        return userList;
    }

    public User insertUser(User user) {
        String sql = "INSERT INTO user ( id,name,deptId,deptName,auth,userType) VALUES(?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, user.getId(), user.getName(), user.getDept_id(),user.getDept_name(),user.getAuth(),user.getType());
        String sql2 = "SELECT * FROM user WHERE id=? ";
        User user2 = jdbcTemplate.queryForObject(sql2, new UserRowMapper(),user.getId());
        return user2;
    }

    public User updateStudentById(long id,User user){
        String sql = "UPDATE user set name=? ,deptId =?,deptName =?,auth =?,userType=? WHERE id=?";
        jdbcTemplate.update(sql, user.getName(),user.getDept_id(),user.getDept_name(),user.getAuth(),user.getType(),id);
        return queryUserById(id);
    }

    public void deleteUserById(long id) {
        String sql = "DELETE FROM user WHERE id=?";
        jdbcTemplate.update(sql, id);
    }
}
